import styled from '@emotion/styled';
import { Button, Empty, Form, Input, Select, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';

import useSyncState from '../hooks/useSyncState';
import AgentService from '@/modules/Agent';

import AgentSelect from './AgentSelect';
import GroupSkillSelect from './GroupSkillSelect';
import GroupSkillRule from './GroupSkillRule';
import SubmitBtn from './SubmitBtn';
import TransferHeader from './TransferHeader';
import { SelectAgentOptions } from '@/modules/interface';

interface InviteAgentProps {
	type: 'sceneTransfer' | 'agentTransfer' | 'inviteAgent' | 'inviteClient';
	onCancel?: () => void;
	onDropdown: () => void;
	onScroll: () => void;
	changeGroupSkill: (value: any) => void;
	submit: (data: { agentName?: string; groups: { id: number; name: string }[] | null; mode: 'agent' | 'groupSkill' }) => void;
	inviteAgentError?: string;
	groupSkillError?: string;
	requestDatasource?: boolean;
	selectAgentOptions: SelectAgentOptions[];
}

const Label = styled.p`
	padding: 10px 0;
	font-size: 13px;
	color: #202020;
	margin: 0;
`;

const BtnBox = styled.div`
	margin-top: 28px;
	text-align: right;
	.ant-btn {
		border-radius: 4px;
	}
	.ant-btn-default {
		background: #fff !important;
		color: #444 !important;
	}
`;

const ErrorText = styled.p`
	font-size: 12px;
	color: #f8646a;
`;
const FormSelectMultiple = styled(Select)`
	width: 100%;
	.ant-select-selector {
		height: 40px !important;
		background-color: #f6f6f6 !important;
	}
	.ant-select-selection-placeholder {
		line-height: 40px !important;
	}
	.ant-select-selection-item {
		/* line-height: 20px !important; */
	}
	input {
		height: 40px !important;
	}
`;

const LoadingText = styled.span`
	color: #bfbfbf;
`;

const SelectedDesc = styled.div`
	padding: 10px;
	box-sizing: border-box;
	background-color: #f6f6f6;
	border-radius: 4px;
	min-height: 40px;
`;

const AgentNoSelectContainer = styled.div``;

const InviteAgent = (props: InviteAgentProps) => {
	useEffect(() => {
		if (AgentService.bizScenarioId) {
			AgentService.fetchGroupWithBizscenariosID(parseInt(AgentService.bizScenarioId), true);
		}
	}, [props]);

	const { inviteAgentError, groupSkillError, onCancel, submit, onDropdown, onScroll, selectAgentOptions, requestDatasource = false } = props;
	const { t } = useTranslation();

	const [selectedGroupSkill, setSelectedGroupSkill] = useSyncState<{ id: number; name: string }[]>([]);
	const [headerOptions, setHeaderOptions] = useState<{ label: string; value: string; disable?: boolean | undefined }[]>(
		AgentService.getTransferHeaderOptions().filter(item => item.value !== 'default')
	);
	const [defaultChecked, setDefaultChecked] = useState<'agent' | 'groupSkill'>('agent');
	const [form] = Form.useForm();

	const changeGroupSkill = (value: any, options: any) => {
		const list = options.map((item: any) => ({ id: item.value, name: item.children }));
		setSelectedGroupSkill(list);
		props.changeGroupSkill(list);
	};

	const headerChangeHandler = (value: 'agent' | 'groupSkill') => {
		setDefaultChecked(value);
	};

	const onFinish = (values: any) => {
		const { no, groupSkill = [] } = values;
		if (groupSkill.length !== 0) {
			const list = AgentService.getGroupSkill().filter(v => groupSkill.indexOf(v.id) !== -1);
			let groups: { id: number; name: string }[] = [];
			groupSkill.forEach((v: number) => {
				const group = list.find(item => item.id === v);
				if (group) {
					groups.push({ id: group?.id, name: group.name });
				}
			});
			submit({ agentName: no, groups, mode: defaultChecked });
		} else {
			submit({ agentName: no, groups: null, mode: defaultChecked });
		}
	};

	const onRest = () => {
		onCancel && onCancel();
	};

	useEffect(() => {
		let no = form.getFieldValue('no');
		if (!selectAgentOptions.find(item => item.label === no)) {
			form.setFieldValue('no', undefined);
		}
	}, [selectAgentOptions]);

	const getFormItem = () => {
		return (
			<>
				<TransferHeader defaultChecked={defaultChecked} options={headerOptions} onChange={headerChangeHandler} />
				{getItem()}
			</>
		);
	};

	const getTips = () => {
		return <LoadingText>{t('load-datasource')}</LoadingText>;
	};

	const getNotFountView = () => {
		if (requestDatasource) {
			return (
				<Spin size="small" tip={getTips()} spinning={requestDatasource}>
					<div style={{ height: '60px' }}></div>
				</Spin>
			);
		} else {
			if (selectAgentOptions.length === 0) {
				return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('agent-list-empty')} />;
			}
		}
	};

	const getItem = () => {
		if (defaultChecked === 'agent')
			return (
				<AgentSelect
					onDropdown={onDropdown}
					onScroll={onScroll}
					notFoundContent={getNotFountView()}
					options={selectAgentOptions}
					name={'no'}
					error={inviteAgentError}
					placeholder={t('select-transfer-invite-placeholder') || ''}
				/>
			);
		if (defaultChecked === 'groupSkill')
			return (
				<>
					<GroupSkillSelect error={groupSkillError} list={AgentService.getGroupSkill()} name="groupSkill" changeGroupSkill={changeGroupSkill} />
					{selectedGroupSkill().length !== 0 ? <GroupSkillRule list={selectedGroupSkill()} /> : null}
				</>
			);
	};

	return (
		<>
			<Form layout="vertical" onFinish={onFinish} form={form}>
				{getFormItem()}
				<SubmitBtn onReset={onRest} />
			</Form>
		</>
	);
};

export default InviteAgent;
